package com.blog.backend.annotation.anoConfig;

import com.blog.backend.annotation.CheckMobile;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author fanggs
 * @Date 2021/7/22 0022 16:29
 */
public class IsMobileValidator implements ConstraintValidator<CheckMobile,String> {
    //用于获取校检字段是否可以为空
    private boolean required=false;

    private static final Pattern mobilePattern= Pattern.compile("^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$");

    @Override
    public void initialize(CheckMobile constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (required){
            Matcher matcher=mobilePattern.matcher(value);
            return matcher.matches();
        }else {
            return false;
        }
    }
}
